<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 输入框位置 -->
      <el-row :gutter="10" type="flex" justify="space-between">
        <el-col :span="4" class="addUser">
          <el-button type="primary" @click="addCateDialogShow">添加分类</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <zk-table
            ref="table"
            sum-text="sum"
            index-text="序号"
            :show-index="true"
            :data="cateList"
            empty-text="暂无数据"
            :tree-type="true"
            :columns="columns"
            label="cat_name"
            :selection-type="false"
            :expand-type="false"
            :border="true"
          >
            <!-- 是否有效 -->
            <template slot="isok" slot-scope="scope">
              <i
                class="el-icon-success"
                v-if="scope.row.cat_deleted == false"
                style="color:green;font-size:16px;text-align:center"
              ></i>
              <i class="el-icon-error" style="color:red;font-size:16px;text-align:cente" v-else></i>
            </template>
            <template slot="order" slot-scope="scope">
              <el-tag type="success" v-if="scope.row.cat_level == 0">一级</el-tag>
              <el-tag type="info" v-else-if="scope.row.cat_level == 1">二级</el-tag>
              <el-tag type="warning" v-else>三级</el-tag>
            </template>
            <template slot="option" slot-scope="operation">
              <!-- 修改用户信息 -->
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="showEditDialog(operation.row)"
              >编辑</el-button>
              <!-- 删除用户 -->
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="deleteCate(operation.row)"
              >删除</el-button>
            </template>
          </zk-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[1, 2, 5, 8]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </el-col>
      </el-row>
    </el-card>

    <!-- 弹出添加分类的对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="dialogVisible_addCateForm"
      width="450px"
      @close="dialogAddCateClose"
      size="medium"
    >
      <el-form
        :model="addCateForm"
        :rules="rules_addCateForm"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>

        <el-form-item label="父级分类">
          <el-cascader
            expand-trigger="hover"
            :props="cascaderProps"
            :options="parentCateList"
            v-model="selectedKeys"
            @change="parentCateChange"
            clearable
            change-on-select
            filterable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible_addCateForm = false">取 消</el-button>
        <el-button type="primary" @click="addCateSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // axios获取到的后台数据数组
      cateList: [],
      //   查询列表条件
      queryInfo: {
        //   分类列表
        type: 3,
        // 当前页码
        pagenum: 1,
        // 每页显示多少条
        pagesize: 5
      },
      //   总数据条数
      total: 1,
      //   为table指定列的定义
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
          width: "auto",
          headerAlign: "center",
          align: "center"
        },
        {
          label: "是否有效",
          //   表示将当前列定义为模板列
          type: "template",
          headerAlign: "center",
          align: "center",
          template: "isok"
        },
        {
          label: "排序",
          //   表示将当前列定义为模板列
          type: "template",
          template: "order",
          headerAlign: "center",
          align: "center",
          width: "100px"
        },
        {
          label: "操作",
          //   表示将当前列定义为模板列
          type: "template",
          template: "option",
          headerAlign: "center",
          align: "center",
          width: "300px"
        }
      ],
      //   添加分类的form数据区域
      addCateForm: {
        //   父级id
        cat_pid: 0,
        // 要添加的分类名称
        cat_name: "",
        // 分类层级
        cat_level: 0
      },
      //  表单校验
      rules_addCateForm: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
      },
      //   添加分类的显示控制开关
      dialogVisible_addCateForm: false,
      //   父级分类的下拉列表
      parentCateList: [],
      // 下拉列表的:props数据源
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      //选择父级组件的id数组
      selectedKeys: []
    };
  },
  created: function() {
    this.getCateList();
  },
  methods: {
    //获取商品分类数据
    getCateList: async function() {
      const { data: res } = await this.$http.get("/categories", {
        params: this.queryInfo
      });
      if (res.meta.status !== 200) {
        this.$message.error("获取商品数据失败");
        return;
      }
      this.cateList = res.data.result;
      this.total = res.data.total;
    },
    handleSizeChange: function(val) {
      // pagesize的改变
      this.queryInfo.pagesize = val;
      const res = this.getCateList();
    },
    handleCurrentChange: function(val) {
      // 当前页码
      this.queryInfo.pagenum = val;
      this.getCateList();
    },
    //显示添加的对话框
    addCateDialogShow: function() {
      this.getParentCateList();
      this.dialogVisible_addCateForm = true;
    },
    getParentCateList: async function() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 }
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取父级分类数据失败");
      }
      this.parentCateList = res.data;
      console.log(res.data);
    },
    //选择项发生变化触发
    parentCateChange: function() {
      //   如果selectedKeys的数组长度大于0,选中了父级分类
      console.log(this.selectedKeys);
      console.log(this.selectedKeys.length);

      if (this.selectedKeys.length > 0) {
        //父级分类的id
        this.addCateForm.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ];
        //为当前分类的等级赋值
        this.addCateForm.cat_level = this.selectedKeys.length;
        return;
      } else {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      }
    },
    addCateSubmit: function() {
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) {
          this.$message.warning("请检查输入的信息是否有误!");
          return;
        }
        const { data: res } = await this.$http.post(
          "/categories",
          this.addCateForm
        );
        if (res.meta.status !== 201) {
          this.$message.error("创建分类失败了!");
          return;
        }
        this.$message.success("创建分类成功了!");
        this.dialogVisible_addCateForm = false;
      });
    },
    dialogAddCateClose: function() {
      // 关闭弹出的对话框
      this.$refs.addCateFormRef.resetFields();
      this.selectedKeys = [];
      this.addCateForm.cat_pid = 0;
      this.addCateForm.cat_level = 0;
    },
    deleteCate: function(_CateInfo) {
      this.$confirm("此操作将永久删除该分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        lockScroll: false
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            "/categories/" + _CateInfo.cat_id
          );
          if (res.meta.status !== 200) {
            this.$message({
              showClose: true,
              message: "删除失败",
              type: "error"
            });
            return;
          }
          this.$message({
            showClose: true,
            message: "删除成功",
            type: "success"
          });
          this.getCateList();
        })
        .catch(() => {});
    }
  }
};
</script>
<style lang='less' scoped>
.zk-table {
  margin-top: 10px;
}
.el-cascader {
  width: 100%;
}
</style>